<template>
  <div class="task-detail-container">
    <div class="page-header">
      <div class="page-title">
        <el-button 
          :icon="ArrowLeft"
          type="text"
          @click="goBack"
        >返回</el-button>
        <h2>{{ taskTitle }}</h2>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showBreakdownDialog">
          版本管理
        </el-button>
        <el-button type="primary" @click="showAddSubtaskDialog" :disabled="!hasActiveBreakdownVersion">
          添加子任务
        </el-button>
        <el-button type="success" @click="goToTaskProgress">
          进度管理
        </el-button>
        <el-button type="warning" @click="goToTaskDependencies">
          依赖管理
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading" class="task-info">
      <template #header>
        <div class="card-header">
          <span>任务信息</span>
        </div>
      </template>
      <div v-if="task">
        <div class="info-item">
          <span class="label">任务ID：</span>
          <span>{{ task.id }}</span>
        </div>
        <div class="info-item">
          <span class="label">任务标题：</span>
          <span>{{ task.title }}</span>
        </div>
        <div class="info-item">
          <span class="label">任务描述：</span>
          <span>{{ task.description }}</span>
        </div>
        <div class="info-item">
          <span class="label">创建时间：</span>
          <span>{{ task.created_at }}</span>
        </div>
        <div class="info-item">
          <span class="label">状态：</span>
          <el-tag :type="getStatusType(task.status)">
            {{ getStatusText(task.status) }}
          </el-tag>
        </div>
        <div class="info-item" v-if="task.breakdown_version">
          <span class="label">当前拆分版本：</span>
          <el-tag type="success">V{{ task.breakdown_version.version_number }}</el-tag>
          <span class="version-info">
            (创建于 {{ formatDate(task.breakdown_version.created_at) }}, 
            由 {{ task.breakdown_version.created_by }} 创建)
          </span>
        </div>
        <div class="info-item" v-else>
          <span class="label">拆分版本：</span>
          <el-tag type="info">暂无拆分版本</el-tag>
          <el-button type="primary" size="small" @click="showCreateVersionDialog" style="margin-left: 10px">
            创建拆分版本
          </el-button>
        </div>
      </div>
      <el-empty v-else-if="!loading" description="无法获取任务信息"></el-empty>
    </el-card>

    <div class="section-title">
      <h3>子任务</h3>
      <el-tag v-if="activeBreakdownVersion" type="success">当前显示版本: V{{ activeBreakdownVersion.version_number }}</el-tag>
    </div>

    <!-- 子任务树形结构 -->
    <el-card class="subtasks-tree">
      <div v-if="!hasSubtasks && !loading" class="no-data-message">
        <template v-if="hasActiveBreakdownVersion">
          暂无子任务，请使用"添加子任务"按钮添加新的子任务
        </template>
        <template v-else>
          任务没有活跃的拆分版本，请先创建或激活拆分版本
          <div class="action-buttons">
            <el-button type="primary" size="small" @click="showCreateVersionDialog">
              创建拆分版本
            </el-button>
            <el-button type="info" size="small" @click="showBreakdownDialog">
              管理版本
            </el-button>
          </div>
        </template>
      </div>
      <el-tree
        v-else
        :data="subtasks"
        node-key="id"
        default-expand-all
        :props="{
          label: 'title',
          children: 'children'
        }"
      >
        <template #default="{ node, data }">
          <div class="subtask-node">
            <div class="subtask-info">
              <span v-if="data.is_atomic" class="atomic-task-link" @click="goToAtomicTask(data)">
                {{ data.title }}
              </span>
              <span v-else>{{ data.title }}</span>
              <el-tag size="small" :type="getStatusType(data.status)" class="status-tag">
                {{ getStatusText(data.status) }}
              </el-tag>
            </div>
            <div class="subtask-actions">
              <el-button 
                v-if="!data.is_atomic"
                type="primary" 
                size="small"
                @click="addChildToSubtask(data)"
              >
                添加
              </el-button>
              <el-button 
                type="success" 
                size="small"
                @click="goToAtomicTask(data)"
                v-if="data.is_atomic"
              >
                执行
              </el-button>
              <el-button 
                type="warning" 
                size="small"
                @click="editSubtask(data)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="confirmDeleteSubtask(data)"
              >
                删除
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>

    <!-- 添加子任务对话框 -->
    <el-dialog
      v-model="addSubtaskDialogVisible"
      title="添加子任务"
      width="500px"
    >
      <el-form :model="newSubtask" label-width="100px">
        <el-form-item label="任务名称" required>
          <el-input v-model="newSubtask.title" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input 
            v-model="newSubtask.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入任务描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否为原子任务">
          <el-switch v-model="newSubtask.is_atomic"></el-switch>
        </el-form-item>
        <el-form-item label="预计工时(小时)" v-if="newSubtask.is_atomic">
          <el-input-number 
            v-model="newSubtask.estimated_hours" 
            :min="0.5" 
            :max="40"
            :step="0.5"
          ></el-input-number>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="addSubtaskDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddSubtask" :loading="submittingSubtask">
          确认添加
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑子任务对话框 -->
    <el-dialog
      v-model="editSubtaskDialogVisible"
      title="编辑子任务"
      width="500px"
    >
      <el-form :model="editingSubtask" label-width="100px">
        <el-form-item label="任务名称" required>
          <el-input v-model="editingSubtask.title" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input 
            v-model="editingSubtask.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入任务描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否为原子任务">
          <el-switch v-model="editingSubtask.is_atomic"></el-switch>
        </el-form-item>
        <el-form-item label="预计工时(小时)" v-if="editingSubtask.is_atomic">
          <el-input-number 
            v-model="editingSubtask.estimated_hours" 
            :min="0.5" 
            :max="40"
            :step="0.5"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select v-model="editingSubtask.status">
            <el-option label="待处理" value="pending"></el-option>
            <el-option label="进行中" value="in_progress"></el-option>
            <el-option label="已完成" value="completed"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editSubtaskDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditSubtask" :loading="submittingEdit">
          保存修改
        </el-button>
      </template>
    </el-dialog>

    <!-- 执行任务对话框 -->
    <el-dialog
      v-model="executeDialogVisible"
      title="执行任务"
      width="500px"
    >
      <p>任务: {{ selectedTask?.title }}</p>
      <p>描述: {{ selectedTask?.description }}</p>
      
      <el-form :model="executeForm" label-width="100px">
        <el-form-item label="执行方式">
          <el-radio-group v-model="executeForm.executor">
            <el-radio label="manual">人工执行</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执行结果" v-if="executeForm.executor === 'manual'">
          <el-input 
            v-model="executeForm.result" 
            type="textarea" 
            :rows="4"
            placeholder="请输入任务执行结果"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="executeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExecuteTask" :loading="submitting">
          确认执行
        </el-button>
      </template>
    </el-dialog>

    <!-- 任务拆分版本管理对话框 -->
    <el-dialog
      v-model="breakdownDialogVisible"
      title="任务拆分版本管理"
      width="850px"
    >
      <div v-loading="loadingVersions">
        <div class="version-header">
          <h3>任务拆分版本列表</h3>
          <el-button type="primary" size="small" @click="showCreateVersionDialog">
            创建新版本
          </el-button>
        </div>
        
        <el-table :data="breakdownVersions" style="width: 100%">
          <el-table-column prop="version_number" label="版本号" width="100">
            <template #default="scope">
              V{{ scope.row.version_number }}
            </template>
          </el-table-column>
          <el-table-column prop="created_by" label="创建者" width="120"></el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="200">
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
                {{ scope.row.status === 'active' ? '活跃' : '归档' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="total_subtasks" label="子任务数" width="100"></el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <div class="action-buttons-container">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="viewVersionDetail(scope.row.id)"
                >
                  查看
                </el-button>
                <el-button 
                  v-if="scope.row.status !== 'active'"
                  type="success" 
                  size="small"
                  @click="activateVersion(scope.row.id)"
                >
                  激活
                </el-button>
                <el-button 
                  v-if="scope.row.status !== 'active'"
                  type="danger" 
                  size="small"
                  @click="confirmDeleteVersion(scope.row)"
                >
                  删除
                </el-button>
                <div v-if="scope.row.status === 'active'" class="placeholder-button"></div>
                <div v-if="scope.row.status === 'active'" class="placeholder-button"></div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <div v-if="breakdownVersions.length === 0 && !loadingVersions" class="no-versions">
          <p>暂无拆分版本，请点击"创建新版本"按钮创建</p>
        </div>
      </div>
    </el-dialog>

    <!-- 创建拆分版本对话框 -->
    <el-dialog
      v-model="createVersionDialogVisible"
      title="创建任务拆分版本"
      width="550px"
    >
      <el-form :model="newVersion" label-width="100px">
        <el-form-item label="创建者">
          <el-input v-model="newVersion.username" placeholder="请输入创建者名称"></el-input>
        </el-form-item>
        
        <el-form-item label="子任务结构">
          <el-tabs v-model="newVersion.inputType">
            <el-tab-pane label="简单结构" name="simple">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入子任务名称，每行一个任务"
                v-model="newVersion.simpleInput"
              ></el-input>
            </el-tab-pane>
            <el-tab-pane label="JSON结构" name="json">
              <el-input
                type="textarea"
                :rows="5"
                placeholder="请输入JSON格式的任务结构"
                v-model="newVersion.jsonInput"
              ></el-input>
              <div class="json-example">
                <small>示例格式: [{"title": "子任务1", "children": [{"title": "子任务1.1"}]}]</small>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer-buttons">
          <el-button @click="createVersionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreateVersion" :loading="submittingVersion">
            确认创建
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看拆分版本详情对话框 -->
    <el-dialog
      v-model="versionDetailDialogVisible"
      :title="`拆分版本详情 (V${selectedVersion?.version_number || ''})`"
      width="850px"
    >
      <div v-loading="loadingVersionDetail">
        <div class="version-info-header">
          <div class="version-basic-info">
            <p><strong>创建者:</strong> {{ selectedVersion?.created_by || '未知' }}</p>
            <p><strong>创建时间:</strong> {{ selectedVersion ? formatDate(selectedVersion.created_at) : '' }}</p>
            <p><strong>状态:</strong> 
              <el-tag :type="selectedVersion?.status === 'active' ? 'success' : 'info'">
                {{ selectedVersion?.status === 'active' ? '活跃' : '归档' }}
              </el-tag>
            </p>
          </div>
        </div>
        
        <div class="subtasks-section">
          <h3>子任务列表</h3>
          <el-tree
            v-if="versionSubtasks.length > 0"
            :data="versionSubtasks"
            node-key="id"
            default-expand-all
            :props="{
              label: 'title',
              children: 'children'
            }"
          >
            <template #default="{ node, data }">
              <div class="subtask-node">
                <div class="subtask-info">
                  <span>{{ data.title }}</span>
                  <el-tag size="small" :type="getStatusType(data.status)" class="status-tag">
                    {{ getStatusText(data.status) }}
                  </el-tag>
                </div>
                <div class="subtask-meta">
                  <span v-if="data.is_atomic">
                    <el-tag size="small" type="info">原子任务</el-tag>
                  </span>
                  <span v-if="data.estimated_hours">
                    工时: {{ data.estimated_hours }}h
                  </span>
                </div>
              </div>
            </template>
          </el-tree>
          <el-empty v-else description="该版本暂无子任务"></el-empty>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer-buttons">
          <el-button @click="versionDetailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="selectedVersion && selectedVersion.status !== 'active'"
            type="success" 
            @click="activateVersionAndClose(selectedVersion.id)"
          >
            激活此版本
          </el-button>
          <el-button 
            v-if="selectedVersion && selectedVersion.status !== 'active'"
            type="danger" 
            @click="confirmDeleteVersionAndClose(selectedVersion)"
          >
            删除此版本
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import {
  getTaskDetail,
  getTaskBreakdownVersions,
  getBreakdownVersionDetail,
  manualBreakdownTask,
  updateBreakdownVersionStatus,
  addSubtaskByVersion,
  updateSubtask,
  executeTask as executeTaskApi,
  deleteSubtask,
  activateBreakdownVersion,
  deleteBreakdownVersion
} from '@/api/task';
import { formatDate } from '@/utils/date';

export default {
  name: 'TaskDetail',
  setup() {
    // 路由和导航
    const route = useRoute();
    const router = useRouter();
    const taskId = computed(() => Number(route.params.id));

    // 数据状态
    const task = ref(null);
    const loading = ref(true);
    const subtasks = ref([]);
    const breakdownVersions = ref([]);
    const loadingVersions = ref(false);
    const versionSubtasks = ref([]);
    const loadingVersionDetail = ref(false);

    // 计算属性
    const taskTitle = computed(() => task.value?.title || '任务详情');
    const hasSubtasks = computed(() => subtasks.value && subtasks.value.length > 0);
    const hasActiveBreakdownVersion = computed(() => !!activeBreakdownVersion.value);
    const activeBreakdownVersion = computed(() => {
      // 从所有拆分版本中找到活跃状态的版本
      if (breakdownVersions.value && breakdownVersions.value.length > 0) {
        return breakdownVersions.value.find(v => v.status === 'active') || null;
      }
      return null;
    });

    // 拆分版本相关状态
    const breakdownDialogVisible = ref(false);
    const createVersionDialogVisible = ref(false);
    const versionDetailDialogVisible = ref(false);
    const selectedVersion = ref(null);
    const newVersion = ref({
      username: '',
      inputType: 'simple',
      simpleInput: '',
      jsonInput: ''
    });
    const submittingVersion = ref(false);

    // 子任务相关状态
    const addSubtaskDialogVisible = ref(false);
    const editSubtaskDialogVisible = ref(false);
    const executeDialogVisible = ref(false);
    const selectedTask = ref(null);
    const parentTask = ref(null);
    const newSubtask = ref({
      title: '',
      description: '',
      is_atomic: false,
      estimated_hours: 1
    });
    const editingSubtask = ref({
      id: null,
      title: '',
      description: '',
      is_atomic: false,
      estimated_hours: 1,
      status: 'pending'
    });
    const executeForm = ref({
      executor: 'manual',
      result: ''
    });
    const submittingSubtask = ref(false);
    const submittingEdit = ref(false);
    const submitting = ref(false);

    // 初始化
    onMounted(() => {
      loadTaskData();
    });

    // 加载任务所有数据
    const loadTaskData = async () => {
      loading.value = true;
      try {
        // 先加载任务基本信息
        await loadTaskDetail();
        // 加载所有拆分版本
        await loadBreakdownVersions();
        // 加载活跃版本下的子任务
        await loadActiveVersionSubtasks();
      } catch (error) {
        console.error('加载任务数据错误:', error);
        ElMessage.error('加载任务数据出错');
      } finally {
        loading.value = false;
      }
    };

    // 获取任务详情
    const loadTaskDetail = async () => {
      try {
        const response = await getTaskDetail(taskId.value);
        if (response.data && response.data.status === 'success') {
          task.value = response.data.data;
        } else {
          ElMessage.error('获取任务详情失败');
        }
      } catch (error) {
        console.error('获取任务详情错误:', error);
        ElMessage.error('获取任务详情出错');
      }
    };

    // 获取拆分版本列表
    const loadBreakdownVersions = async () => {
      loadingVersions.value = true;
      try {
        const response = await getTaskBreakdownVersions(taskId.value);
        if (response.data && response.data.status === 'success') {
          breakdownVersions.value = response.data.data;
        } else {
          ElMessage.error('获取拆分版本列表失败');
        }
      } catch (error) {
        console.error('获取拆分版本列表错误:', error);
        ElMessage.error('获取拆分版本列表出错');
      } finally {
        loadingVersions.value = false;
      }
    };

    // 加载活跃版本下的子任务
    const loadActiveVersionSubtasks = async () => {
      if (!activeBreakdownVersion.value) {
        subtasks.value = [];
        return;
      }

      try {
        const response = await getBreakdownVersionDetail(activeBreakdownVersion.value.id);
        if (response.data && response.data.status === 'success') {
          subtasks.value = response.data.data.subtasks || [];
        } else {
          subtasks.value = [];
          ElMessage.error('获取子任务失败');
        }
      } catch (error) {
        console.error('获取子任务错误:', error);
        ElMessage.error('获取子任务出错');
        subtasks.value = [];
      }
    };

    // 获取特定拆分版本详情
    const loadVersionDetail = async (versionId) => {
      loadingVersionDetail.value = true;
      try {
        const response = await getBreakdownVersionDetail(versionId);
        if (response.data && response.data.status === 'success') {
          selectedVersion.value = response.data.data;
          versionSubtasks.value = response.data.data.subtasks || [];
        } else {
          ElMessage.error('获取拆分版本详情失败');
        }
      } catch (error) {
        console.error('获取拆分版本详情错误:', error);
        ElMessage.error('获取拆分版本详情出错');
      } finally {
        loadingVersionDetail.value = false;
      }
    };

    // 显示拆分版本管理弹窗
    const showBreakdownDialog = () => {
      breakdownDialogVisible.value = true;
      loadBreakdownVersions();
    };

    // 显示创建拆分版本弹窗
    const showCreateVersionDialog = () => {
      createVersionDialogVisible.value = true;
      breakdownDialogVisible.value = false;
      newVersion.value = {
        username: '',
        inputType: 'simple',
        simpleInput: '',
        jsonInput: ''
      };
    };

    // 提交创建拆分版本
    const submitCreateVersion = async () => {
      submittingVersion.value = true;
      try {
        let tasksData;
        if (newVersion.value.inputType === 'simple') {
          // 解析简单文本输入
          const lines = newVersion.value.simpleInput.split('\n').filter(line => line.trim());
          tasksData = lines.map(line => ({ title: line.trim() }));
        } else {
          // 解析JSON输入
          try {
            tasksData = JSON.parse(newVersion.value.jsonInput);
          } catch (error) {
            ElMessage.error('JSON格式无效，请检查输入');
            submittingVersion.value = false;
            return;
          }
        }
        
        const response = await manualBreakdownTask(taskId.value, {
          username: newVersion.value.username || '系统用户',
          tasks: tasksData
        });
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success('拆分版本创建成功');
          createVersionDialogVisible.value = false;
          // 重新加载任务数据
          await loadBreakdownVersions();
          await loadActiveVersionSubtasks();
        } else {
          ElMessage.error(response.data?.message || '创建失败');
        }
      } catch (error) {
        console.error('创建拆分版本错误:', error);
        ElMessage.error('创建拆分版本出错');
      } finally {
        submittingVersion.value = false;
      }
    };

    // 查看拆分版本详情
    const viewVersionDetail = (versionId) => {
      versionDetailDialogVisible.value = true;
      loadVersionDetail(versionId);
    };

    // 显示添加子任务弹窗
    const showAddSubtaskDialog = () => {
      parentTask.value = null;
      newSubtask.value = {
        title: '',
        description: '',
        is_atomic: false,
        estimated_hours: 1
      };
      addSubtaskDialogVisible.value = true;
    };

    // 显示添加子任务到特定父任务
    const addChildToSubtask = (parentSubtask) => {
      parentTask.value = parentSubtask;
      newSubtask.value = {
        title: '',
        description: '',
        is_atomic: false,
        estimated_hours: 1
      };
      addSubtaskDialogVisible.value = true;
    };

    // 提交添加子任务
    const submitAddSubtask = async () => {
      if (!newSubtask.value.title.trim()) {
        ElMessage.warning('请输入任务名称');
        return;
      }
      
      submittingSubtask.value = true;
      
      try {
        const subtaskData = {
          title: newSubtask.value.title,
          description: newSubtask.value.description,
          is_atomic: newSubtask.value.is_atomic,
          estimated_hours: newSubtask.value.is_atomic ? newSubtask.value.estimated_hours : undefined,
          parent_task_id: parentTask.value ? parentTask.value.id : null
        };
        
        // 使用活跃拆分版本ID添加子任务
        if (!activeBreakdownVersion.value) {
          ElMessage.error('没有活跃的拆分版本，无法添加子任务');
          submittingSubtask.value = false;
          return;
        }
        
        const versionId = activeBreakdownVersion.value.id;
        const response = await addSubtaskByVersion(versionId, subtaskData);
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success('子任务添加成功');
          addSubtaskDialogVisible.value = false;
          // 重新加载活跃版本下的子任务
          await loadActiveVersionSubtasks();
        } else {
          ElMessage.error(response.data?.message || '添加失败');
        }
      } catch (error) {
        console.error('添加子任务错误:', error);
        ElMessage.error('添加子任务出错');
      } finally {
        submittingSubtask.value = false;
      }
    };

    // 编辑子任务
    const editSubtask = (subtask) => {
      editingSubtask.value = {
        id: subtask.id,
        title: subtask.title,
        description: subtask.description || '',
        is_atomic: subtask.is_atomic,
        estimated_hours: subtask.estimated_hours || 1,
        status: subtask.status || 'pending'
      };
      editSubtaskDialogVisible.value = true;
    };

    // 提交编辑子任务
    const submitEditSubtask = async () => {
      if (!editingSubtask.value.title.trim()) {
        ElMessage.warning('请输入任务名称');
        return;
      }
      
      submittingEdit.value = true;
      
      try {
        const updateData = {
          title: editingSubtask.value.title,
          description: editingSubtask.value.description,
          is_atomic: editingSubtask.value.is_atomic,
          estimated_hours: editingSubtask.value.is_atomic ? editingSubtask.value.estimated_hours : undefined,
          status: editingSubtask.value.status
        };
        
        const response = await updateSubtask(editingSubtask.value.id, updateData);
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success('子任务更新成功');
          editSubtaskDialogVisible.value = false;
          // 重新加载子任务
          await loadActiveVersionSubtasks();
        } else {
          ElMessage.error(response.data?.message || '更新失败');
        }
      } catch (error) {
        console.error('更新子任务错误:', error);
        ElMessage.error('更新子任务出错');
      } finally {
        submittingEdit.value = false;
      }
    };

    // 执行任务
    const executeTask = (subtask) => {
      selectedTask.value = subtask;
      executeForm.value = {
        executor: 'manual',
        result: ''
      };
      executeDialogVisible.value = true;
    };

    // 提交执行任务
    const submitExecuteTask = async () => {
      if (!selectedTask.value) return;
      
      submitting.value = true;
      
      try {
        const response = await executeTaskApi(
          selectedTask.value.id,
          executeForm.value.executor,
          executeForm.value.result
        );
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success('任务执行成功');
          executeDialogVisible.value = false;
          // 重新加载任务详情
          loadTaskData();
        } else {
          ElMessage.error(response.data?.message || '执行失败');
        }
      } catch (error) {
        console.error('执行任务错误:', error);
        ElMessage.error('执行任务出错');
      } finally {
        submitting.value = false;
      }
    };

    // 确认删除子任务
    const confirmDeleteSubtask = (subtask) => {
      ElMessageBox.confirm(
        `确定要删除子任务"${subtask.title}"吗？删除后无法恢复。`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await deleteSubtask(subtask.id);
          if (response.data && response.data.status === 'success') {
            ElMessage.success('子任务删除成功');
            // 重新加载子任务
            await loadActiveVersionSubtasks();
          } else {
            ElMessage.error(response.data?.message || '删除失败');
          }
        } catch (error) {
          console.error('删除子任务错误:', error);
          ElMessage.error('删除子任务出错');
        }
      }).catch(() => {
        // 用户取消删除操作
      });
    };

    // 跳转到原子任务详情页
    const goToAtomicTask = (subtask) => {
      if (!subtask || !subtask.id) {
        ElMessage.warning('任务ID不存在，无法跳转');
        return;
      }
      
      try {
        // 确保在跳转前检查subtask.id是否有效
        const taskId = Number(subtask.id);
        if (isNaN(taskId) || taskId <= 0) {
          ElMessage.warning('无效的任务ID');
          return;
        }
        
        // 检查是否为原子任务
        if (!subtask.is_atomic) {
          ElMessage.warning('只能查看原子任务详情');
          return;
        }
        
        // 使用路由导航
        router.push({
          name: 'AtomicTaskDetail',
          params: { id: taskId }
        }).catch(err => {
          // 捕获路由错误并提供反馈
          if (err.name === 'NavigationDuplicated') {
            // 忽略重复导航错误
            return;
          }
          console.error('导航错误:', err);
          ElMessage.error('导航失败，请检查路由配置');
        });
      } catch (error) {
        console.error('跳转错误:', error);
        ElMessage.error('跳转到原子任务详情页出错');
      }
    };

    // 跳转到任务进度管理页
    const goToTaskProgress = () => {
      router.push(`/tasks/${taskId.value}/progress`);
    };

    // 跳转到任务依赖管理页
    const goToTaskDependencies = () => {
      router.push(`/tasks/${taskId.value}/dependencies`);
    };

    // 返回
    const goBack = () => {
      router.back();
    };

    // 工具方法：获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'pending': 'info',
        'in_progress': 'warning',
        'completed': 'success',
        'blocked': 'danger',
        'review': 'primary',
        'failed': 'danger'
      };
      return statusMap[status] || 'info';
    };

    // 工具方法：获取状态文本
    const getStatusText = (status) => {
      const statusTextMap = {
        'pending': '待处理',
        'in_progress': '进行中',
        'completed': '已完成',
        'blocked': '已阻塞',
        'review': '待审核',
        'failed': '失败'
      };
      return statusTextMap[status] || '未知状态';
    };

    // 激活版本
    const activateVersion = async (versionId) => {
      try {
        const response = await activateBreakdownVersion(versionId);
        if (response.data && response.data.status === 'success') {
          ElMessage.success('版本激活成功');
          // 重新加载版本列表和任务信息
          await loadBreakdownVersions();
          await loadTaskData();
        } else {
          ElMessage.error(response.data?.message || '激活失败');
        }
      } catch (error) {
        console.error('激活版本错误:', error);
        ElMessage.error('激活版本出错');
      }
    };

    // 确认删除版本
    const confirmDeleteVersion = (version) => {
      ElMessageBox.confirm(
        `确定要删除版本 V${version.version_number} 吗？删除后将无法恢复，其中的所有子任务也将被删除。`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          console.log(`准备删除版本 ID:${version.id}, 版本号:${version.version_number}`);
          const response = await deleteBreakdownVersion(version.id);
          console.log(`删除版本API返回结果:`, response);
          
          if (response.data && response.data.status === 'success') {
            ElMessage.success('版本删除成功');
            // 重新加载版本列表
            await loadBreakdownVersions();
          } else {
            // 提供更详细的错误信息
            const errorMsg = response.data?.message || '删除失败';
            console.error('删除版本响应错误:', errorMsg, response.data);
            ElMessage.error(errorMsg);
          }
        } catch (error) {
          console.error('删除版本请求错误:', error);
          
          // 详细记录错误信息
          if (error.response) {
            console.error('错误状态码:', error.response.status);
            console.error('错误请求URL:', error.response.config?.url);
            console.error('错误请求方法:', error.response.config?.method);
            console.error('错误响应数据:', error.response.data);
          } else if (error.request) {
            console.error('请求已发送但没有收到响应');
            console.error('请求对象:', error.request);
          } else {
            console.error('请求设置过程中触发错误:', error.message);
          }
          
          let errorMessage = '删除版本出错';
          if (error.response && error.response.data) {
            errorMessage = error.response.data.message || errorMessage;
          }
          ElMessage.error(errorMessage);
        }
      }).catch((cancelErr) => {
        // 用户取消操作
        console.log('用户取消了删除操作', cancelErr);
      });
    };

    // 激活版本并关闭对话框
    const activateVersionAndClose = async (versionId) => {
      try {
        await activateVersion(versionId);
        versionDetailDialogVisible.value = false;
      } catch (error) {
        console.error('激活版本并关闭对话框错误:', error);
        ElMessage.error('激活版本并关闭对话框出错');
      }
    };

    // 确认删除版本并关闭对话框
    const confirmDeleteVersionAndClose = (version) => {
      ElMessageBox.confirm(
        `确定要删除版本 V${version.version_number} 吗？删除后将无法恢复，其中的所有子任务也将被删除。`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await deleteBreakdownVersion(version.id);
          if (response.data && response.data.status === 'success') {
            ElMessage.success('版本删除成功');
            // 关闭对话框
            versionDetailDialogVisible.value = false;
            // 重新加载版本列表
            await loadBreakdownVersions();
          } else {
            // 提供更详细的错误信息
            const errorMsg = response.data?.message || '删除失败';
            console.error('删除版本响应错误:', errorMsg);
            ElMessage.error(errorMsg);
          }
        } catch (error) {
          console.error('删除版本请求错误:', error);
          let errorMessage = '删除版本出错';
          if (error.response && error.response.data) {
            errorMessage = error.response.data.message || errorMessage;
          }
          ElMessage.error(errorMessage);
        }
      }).catch(() => {
        // 用户取消操作
      });
    };

    return {
      ArrowLeft,
      task,
      loading,
      subtasks,
      taskTitle,
      hasSubtasks,
      hasActiveBreakdownVersion,
      activeBreakdownVersion,
      breakdownVersions,
      loadingVersions,
      breakdownDialogVisible,
      createVersionDialogVisible,
      newVersion,
      submittingVersion,
      addSubtaskDialogVisible,
      editSubtaskDialogVisible,
      executeDialogVisible,
      selectedTask,
      parentTask,
      newSubtask,
      editingSubtask,
      executeForm,
      submittingSubtask,
      submittingEdit,
      submitting,
      versionDetailDialogVisible,
      selectedVersion,
      versionSubtasks,
      loadingVersionDetail,
      formatDate,
      loadTaskData,
      showBreakdownDialog,
      showCreateVersionDialog,
      submitCreateVersion,
      viewVersionDetail,
      showAddSubtaskDialog,
      addChildToSubtask,
      submitAddSubtask,
      editSubtask,
      submitEditSubtask,
      executeTask,
      submitExecuteTask,
      confirmDeleteSubtask,
      goToAtomicTask,
      goToTaskProgress,
      goToTaskDependencies,
      goBack,
      getStatusType,
      getStatusText,
      activateVersion,
      confirmDeleteVersion,
      activateVersionAndClose,
      confirmDeleteVersionAndClose
    };
  }
};
</script>

<style scoped>
.task-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
}

.page-title h2 {
  margin: 0 0 0 10px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.task-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  line-height: 24px;
}

.label {
  font-weight: bold;
  margin-right: 5px;
}

.section-title {
  margin: 20px 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title h3 {
  margin: 0;
  font-size: 18px;
}

.subtasks-tree {
  margin-bottom: 20px;
}

.subtask-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px 0;
}

.subtask-info {
  display: flex;
  align-items: center;
}

.status-tag {
  margin-left: 10px;
}

.subtask-actions {
  display: flex;
  gap: 8px;
}

.no-data-message {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}

.version-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.version-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.el-table {
  margin-bottom: 20px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.no-versions {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.version-info {
  margin-left: 10px;
  font-size: 0.9em;
  color: #606266;
}

.json-example {
  margin-top: 5px;
  color: #909399;
}

.action-buttons {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.atomic-task-link {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
}

.atomic-task-link:hover {
  color: #66b1ff;
}

.version-info-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.version-basic-info p {
  margin: 10px 0;
  font-size: 14px;
  line-height: 1.5;
}

.subtasks-section {
  margin-top: 20px;
}

.subtasks-section h3 {
  margin-bottom: 15px;
}

.subtask-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 0.85em;
  color: #606266;
}

.action-buttons-container {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  align-items: center;
  min-height: 32px;
}

.placeholder-button {
  width: 52px;  /* 与按钮宽度一致 */
  height: 32px; /* 与按钮高度一致 */
  visibility: hidden;
}

/* 固定表格中按钮宽度，使其对齐 */
.el-table .el-button {
  min-width: 52px;
  margin: 0;
}

/* 版本详情对话框中的按钮对齐 */
.el-dialog__footer .el-button {
  min-width: 88px; /* 使底部确认按钮宽度一致 */
}

.dialog-footer-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 